#------------------------------------------------------------------
# Project Senior Project
# name Game.py
# purpose Game run file
#
# authors Chris L'Heureux
# 
# created 1/14/14
# Copyright (C) Chris L'Heureux
# License New BSD\
#
#https://code.google.com/p/seniorprojectgame/
#------------------------------------------------------------------  
import pygame, math, sys, random
from Player import Player
from Enemy import Enemy
#from bullet import Bullet
from goal import Goal
from Block import Block
from HardBlock import HardBlock
from Background import Background
#from gun import Gun
pygame.init()

clock = pygame.time.Clock()

screenWidth = 1024
screenHeight = 768
size = screenWidth, screenHeight

screenSize = screenWidth, screenHeight

menuimg = pygame.image.load("images/World/Background.png")
menurect = menuimg.get_rect()

overimg = pygame.image.load("images/World/gameover.png")
overrect = overimg.get_rect()

fullscreen = False
altFlag = False
GameOver = False
start = False

screen = pygame.display.set_mode(screenSize)

fulscreen = 0

blocksize = [200,200]
playersize = [160,160]

screen = pygame.display.set_mode(size)
bgColor = r,g,b = 0,0,0

blocks = pygame.sprite.Group()
hardBlocks = pygame.sprite.Group()
enemies = pygame.sprite.Group()
goals = pygame.sprite.Group()
backgrounds = pygame.sprite.Group()
players = pygame.sprite.Group()
all = pygame.sprite.OrderedUpdates()

Player.containers = (all, players)
Block.containers = (all, blocks)
Goal.containers = (all, goals)
HardBlock.containers = (all, hardBlocks, blocks)
Enemy.containers = (all, enemies)
Background.containers = (all, blocks)


bg = Background("Images/World/menu.png", size)

def loadLevel(level):
    f = open(level+".lvl", 'r')
    lines = f.readlines()
    f.close()
    
    newlines = []
    
    for line in lines:
        newline = ""
        for c in line:
            if c != "\n":
                newline += c
        newlines += [newline]
        
    for line in newlines:
        print line
    
    for y, line in enumerate(newlines):
        for x, c in enumerate(line):
            if c == "#":
                HardBlock("Images/Blocks/Block1.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "p":
                Block("Images/Blocks/Block2.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
            elif c == "b":
                Goal("Images/Blocks/Block3.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      blocksize)
    
    f = open(level+".tng", 'r')
    lines = f.readlines()
    f.close()
    
    newlines = []
    
    for line in lines:
        newline = ""
        for c in line:
            if c != "\n":
                newline += c
        newlines += [newline]
        
    for line in newlines:
        print line
    
    for y, line in enumerate(newlines):
        for x, c in enumerate(line):
            if c == "@":
                player = Player([(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2],
                     playersize,
                     size)
            elif c == "e":
                Enemy("Images/Enemies/Enemy1.png", 
                      [(x*blocksize[0])+blocksize[0]/2, (y*blocksize[1])+blocksize[1]/2], 
                      playersize)
    for each in all.sprites():
        each.fixLocation(player.offsetx, player.offsety)
     
    

levels = ["levels/level1",
          "levels/level2",
          "levels/level3",
          "levels/level4"]


GameOver = False
start = False

#screen = pygame.display.set_mode((screenWidth,screenHeight),fullscreen)
level = 0

def loadNextLevel(level):
    for each in all.sprites():
        each.kill()
    bg = Background("Images/World/Background.png", size)
    screen.blit(bg.image, bg.rect)
    loadLevel(levels[level])
    return level

while True:
    while not start:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            elif event.type == pygame.KEYDOWN:
                if (event.key == pygame.K_RETURN):
                    start = True
                    print "???????"            
        all.update(0,
                   0, 
                   0, 
                   0, 
                   0,
                   0)
        dirty = all.draw(screen)
        pygame.display.update(dirty)
        pygame.display.flip()
        clock.tick(30)

    bg = Background("Images/World/Background.png", size)
    loadLevel(levels[level])
    player1 = players.sprites()[0]
    
    
        
    
    while player1.living and start:
        for event in pygame.event.get():
            print event.type
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                #if event.key == pygame.K_RETURN:
                if event.key == pygame.K_r:
                    for each in all.sprites():
                            each.kill()
                    bg = Background("Images/World/Background.png", size)
                    screen.blit(bg.image, bg.rect)
                    loadLevel(levels[level])
                    player1 = players.sprites()[0]   
                if event.key == pygame.K_p:
                    sys.exit()
                if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
                    print "??????????"
                    player1.direction("right")
                if event.key == pygame.K_a or event.key == pygame.K_LEFT:
                    player1.direction("left")
                if event.key == pygame.K_w or event.key == pygame.K_UP:
                    player1.direction("up")
                if event.key == pygame.K_s or event.key == pygame.K_DOWN:
                    player1.direction("down")
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
                    player1.direction("stop right")
                if event.key == pygame.K_a or event.key == pygame.K_LEFT:
                    player1.direction("stop left")
                if event.key == pygame.K_w or event.key == pygame.K_UP:
                    player1.direction("stop up")
                if event.key == pygame.K_s or event.key == pygame.K_DOWN:
                    player1.direction("stop down")                     
                elif (event.key == pygame.K_RALT or event.key == pygame.K_LALT):
                    altFlag = True
                elif (event.key == pygame.K_RETURN) and altFlag:
                    if fullscreen == 0:
                        fullscreen = pygame.FULLSCREEN
                    else:
                        fullscreen = 0
                    screen = pygame.display.set_mode((screenWidth,screenHeight),fullscreen)
                    pygame.display.flip()
                    altFlag = False
                    
        playersHitBlocks = pygame.sprite.groupcollide(players, hardBlocks, False, False)
        playersHitGoal = pygame.sprite.groupcollide(players, goals, False, False)
        enemiesHitBlocks = pygame.sprite.groupcollide(enemies, hardBlocks, False, False)
        enemiesHitEnemies = pygame.sprite.groupcollide(enemies, enemies, False, False)
        
        for player in playersHitBlocks:
            for block in playersHitBlocks[player]:
                player.collideBlock(block)
                
        for player in playersHitGoal:
            for block in playersHitGoal[player]:
                level = loadNextLevel(level+1)
                if level == 3:
                    print "????????????????????????????????????????"
                    player1 = players.sprites()[0] 
                    bg = Background("Images/World/gameover.png", size)
                else:
                    player1 = players.sprites()[0] 

                
                
        for enemy in enemiesHitBlocks:
            for block in enemiesHitBlocks[enemy]:
                enemy.collideBlock(block)
                
        for enemy in enemiesHitEnemies:
            for otherEnemy in enemiesHitEnemies[enemy]:
                enemy.collideBlock(otherEnemy)
        
        all.update(size,
                   player1.speedx, 
                   player1.speedy, 
                   player1.scrollingx, 
                   player1.scrollingy,
                   player1.realx,
                   player1.realy)
        
        dirty = all.draw(screen)
        pygame.display.update(dirty)
        pygame.display.flip()
        clock.tick(30)
    
    
   
    '''while not player1.living and start:
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()
            elif event.type == pygame.KEYDOWN:
                if (event.key == pygame.K_RETURN):
                    player.retry("yes", (15, [512, 384]))
                    
                    gun = Gun()
                    
                    enemies = []
                    maxEnemies = 15
                    enemyOdds = 1
                    
                    
        screen = pygame.display.set_mode((screenWidth,screenHeight),fullscreen)
        screen.blit(overimg, overrect)
        pygame.display.flip()  '''  
